import { Subject } from 'rxjs';
import { Injectable } from '@angular/core';
import { DataRegister, Workflow } from '../models';
import { BaseService } from './base.service';

@Injectable({
  providedIn: 'root'
})
export class WorkflowService extends BaseService {
  involvedPersonChange$: Subject<any> = new Subject();

  private _currentWorkflow: Workflow;

  get currentWorkflow() {
    return this._currentWorkflow;
  }

  set currentWorkflow(workflow: Workflow) {
    this._currentWorkflow = workflow;
  }

  private currentDataRegisterId: string;

  get CurrentDataRegisterId() {
    return this.currentDataRegisterId;
  }


  setDataRegisterId(id: string) {
    this.currentDataRegisterId = id;
  }


  getWorkflowById(workflowId: string): Promise<Workflow> {
    const url = `api/workflow/${workflowId}`;
    return this.get(url);
  }


  getPageById(pageId: string) {
    const url = `api/page/${pageId}`;
    return this.get(url);
  }


  updateNodeByDataRegister(dataRegister: DataRegister, workflow: Workflow) {
    if (!dataRegister) {
      workflow.workflowNodeItems.forEach((item, index) => {
        item.flowNode.status = index === 0 ? 'process' : 'wait';
      });
    } else if (dataRegister.objectId === workflow.id) {
      const dataNodeItems = dataRegister.data.flowNodesItems;
      workflow.workflowNodeItems.forEach(node => {
        const dataNodeItem = dataNodeItems.find((item: any) => item.flowNodeId === node.flowNodeId);
        if (dataNodeItem) {
          node.flowNode.status = dataNodeItem.status;
          node.disabled = dataNodeItem.disabled;
        }
      });
    }
    return workflow.workflowNodeItems;
  }
}
